package main

import (
	"context"
	"log"
	"os"
	"time"

	pb "neu/liuhy/gorpc/proto"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

const (
	defaultName = "world"
)

func main() {
	// 连接到gRPC服务器
	conn, err := grpc.NewClient(":50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

	// 创建客户端
	c := pb.NewGreeterClient(conn)

	// 获取名称参数
	name := defaultName
	if len(os.Args) > 1 {
		name = os.Args[1]
	}

	// 调用SayHello方法
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", r.Message)

	// 调用SayHelloBatch方法
	ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second)
	defer cancel2()

	batchResp, err := c.SayHelloBatch(ctx2, &pb.HelloBatchRequest{
		Names: []string{"Alice", "Bob", "Charlie"},
	})
	if err != nil {
		log.Fatalf("could not greet batch: %v", err)
	}
	log.Println("Batch greetings:")
	for _, msg := range batchResp.Messages {
		log.Printf("- %s", msg)
	}
}
